

package com.example.actearly_revised;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.actearly_revised.R;


public class SummaryPage extends Activity {
	// handles for layout objects and variables from tab host
	private Button emailButton;
	private TabHomePage parent;
	private static int currentmilestone;
	private static int profile_number;
	private ImageButton leftButton;
	private ImageButton rightButton;
	private TextView currentAge;
	private TextView summaryText;
	private CheckBox EmailDoc;

	private int[] ageID;
	private String[] ageGroups;
	private int ageCounter;

	// answer table options
	final String yes_ans = "yes";
	final String no_ans = "no";
	final String maybe_ans = "notsure";

	// variable needed to start the Expandable List View 
	private ExpandableListView ExpandList;
	private ArrayList<ExpandListGroup> topLevelGroup;
	private ExpandListAdapter ExpAdapter;

	// ArrayList Grabing all relevent Questions/answer combinations for a given milestone
	private ArrayList<QuestionAnswerGroup> QAGroupings = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_summary_page);

		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		leftButton = (ImageButton) findViewById(R.id.leftButton);
		rightButton = (ImageButton) findViewById(R.id.rightButton);
		currentAge= (TextView) findViewById(R.id.currentAge);
		summaryText= (TextView) findViewById(R.id.summaryText);


		parent = (TabHomePage) this.getParent();
		this.currentmilestone = parent.currentmilestone;
		this.profile_number = parent.profile_number;

		// ageGroups = array of ages written nicely
		ageGroups= getResources().getStringArray(R.array.milestoneAges);
		ageID = new int[] {
				2,4,6,9,12,18,24,36,48,60
		};
		ageCounter = IndexOf(this.currentmilestone,ageID);
		currentAge.setText(ageGroups[ageCounter]);

		ExpandList = (ExpandableListView) findViewById(R.id.SummaryExpList);

		LinearLayout pageLayout=(LinearLayout)findViewById(R.id.summaryLayout);

		Typeface customFont = Typeface.createFromAsset(getAssets(), "fonts/futuram.ttf");

		currentAge.setTypeface(customFont);
		summaryText.setTypeface(customFont);

		EmailDoc = (CheckBox) findViewById(R.id.EmailDoc);
		EmailDoc.setTypeface(customFont);
		EmailDoc.setTextSize(18);


		ExpandList
		.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

			QuestionAnswerGroup selected = null;
			int groupSpot;
			ExpandableListView p;

			@Override
			public boolean onChildClick(ExpandableListView parent,
					View v, int groupPosition, int childPosition,
					long id) {
				// v = view within list that was clicked
				// childposition = position within group
				// id = row id of clicked child
				// return: returns true if click was handled

				p = parent;
				LinearLayout top = (LinearLayout) v;

				//	top.setBackgroundColor(0xC9D787);

				TextView sel = (TextView) top.getChildAt(0);

				// get the questionAnswerGroup that was selected
				for(int i = 0; i < QAGroupings.size(); i++){
					// equality won't work with star in milestone text
					String milestone = sel.getText().toString().replace("* ", "");
					if(QAGroupings.get(i).getQuestion().equals(milestone)){
						System.out.println("found match");
						selected = QAGroupings.get(i);
						break;
					}
				}

				groupSpot = groupPosition;
				// List items

				final CharSequence[] items = { "Yes", "No", "Not Sure" };

				// Prepare the list dialog box

				AlertDialog.Builder builder = new AlertDialog.Builder(
						SummaryPage.this);


				SQLogic c = new SQLogic(SummaryPage.this);

				c.open();
				User curr = c.getUserData(profile_number);
				c.close();

				// Set its title
				TextView title = new TextView(SummaryPage.this);
				title.setText("Select an option below to change the milestone\'s answer. \n\n" +
						"* indicates a key milestone. Please discuss this milestone with " +
						"Dr. " + curr.doctor + ".");
				title.setPadding(25, 0, 25, 0);
				title.setTextSize(16.0f);
				title.setTypeface(Typeface.SANS_SERIF);

				// can make custom title here
				builder.setCustomTitle(title);
				//	builder.setTitle("Select an option below to change the question\'s answer \n\n" +
				//			"* indicates a key milestone indicator, please discuss this milestone with " +
				//			"Dr. " + curr.doctor);

				// Set the list items and assign with the click listener

				builder.setItems(items,
						new DialogInterface.OnClickListener() {

					// Click listener, updates database with new answer and puts it in the 
					// appropriate list

					public void onClick(DialogInterface dialog,
							int item) {

						int newGroup = groupSpot;
						SQLogic conn = new SQLogic(SummaryPage.this);
						try{
							conn.open();
						}
						catch(Exception e){
							e.printStackTrace();
						}

						if(item == 0){ // yes was clicked
							// yes group position = 1
							if(groupSpot != 1){
								conn.UpdateAnswer(selected.getQuestionId(), yes_ans, profile_number);
								Toast.makeText(getApplicationContext(),
										"Answer was changed to yes", Toast.LENGTH_SHORT)
										.show();

								newGroup = 1;
							}

						}

						else if(item == 1){ // no was clicked
							// no group position = 0
							if(groupSpot != 0){
								conn.UpdateAnswer(selected.getQuestionId(), no_ans, profile_number);
								Toast.makeText(getApplicationContext(),
										"Answer was changed to No", Toast.LENGTH_SHORT)
										.show();
								newGroup = 0;
							}
						}

						else if(item == 2){ // not sure was clicked
							// not sure group position = 2
							if(groupSpot != 2){
								conn.UpdateAnswer(selected.getQuestionId(), maybe_ans, profile_number);
								Toast.makeText(getApplicationContext(),
										"Answer was changed to Maybe", Toast.LENGTH_SHORT)
										.show();
								newGroup = 2;
							}
						}

						conn.close();

						try{
							// refresh expandable list view
							topLevelGroup = QuestionGroups();
							ExpAdapter = new ExpandListAdapter(SummaryPage.this, topLevelGroup);
							ExpandList.setAdapter(ExpAdapter);
						}
						catch(Exception e){
							e.printStackTrace();
						}

						p.collapseGroup(groupSpot);
						p.expandGroup(newGroup);
					}

				});

				AlertDialog alert = builder.create();

				// display dialog box

				alert.show();

				return true;
			}
		});

		// change age group and refresh expandable list view
		leftButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ageCounter>0)
					ageCounter--;
				currentAge.setText(ageGroups[ageCounter]);
				currentmilestone = ageID[ageCounter];
				parent.currentmilestone = SummaryPage.currentmilestone;

				topLevelGroup = QuestionGroups();
				ExpAdapter = new ExpandListAdapter(SummaryPage.this, topLevelGroup);
				ExpandList.setAdapter(ExpAdapter);
			}
		});

		// change age group and refresh expandable list view
		rightButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ageCounter<ageGroups.length-1)
					ageCounter++;
				currentAge.setText(ageGroups[ageCounter]);
				currentmilestone = ageID[ageCounter];
				parent.currentmilestone = SummaryPage.currentmilestone;

				topLevelGroup = QuestionGroups();
				ExpAdapter = new ExpandListAdapter(SummaryPage.this, topLevelGroup);
				ExpandList.setAdapter(ExpAdapter);
			}
		});

		emailButton = (Button) findViewById(R.id.email);

		// send email 
		emailButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				User curr;
				try{		
					SQLogic c = new SQLogic(SummaryPage.this);
					c.open();
					curr = c.getUserData(SummaryPage.profile_number);
					c.close();  

					String age = ageGroups[ageCounter].replaceAll("years", "year").replaceAll("monthes", "month");
					StringBuilder sb = new StringBuilder();
					sb.append("<b>Notes from " + curr.childname + "\'s " + age +" Milestones:</b> <br><br>" );
					sb.append(getNoteChild().get(0).getName());
					String note = sb.toString();

					Email_Builder newEmail = new Email_Builder(SummaryPage.this, SummaryPage.profile_number,
							EmailGrid(),note);  

					String[] recipients = new String[2];
					recipients[0] = curr.email;
					if(EmailDoc.isChecked()){
						recipients[1] =  curr.docemail;
					}

					Email.emailResultsToUser(SummaryPage.this, curr.childname + "\'s " + age + " Act Early Results", 
							newEmail.setSubject(), null, 
							recipients, null, null);
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
		});  

	}

	@Override
	protected void onResume(){
		super.onResume();
		this.currentmilestone = parent.currentmilestone;
		ageCounter = IndexOf(SummaryPage.currentmilestone,ageID);
		currentAge.setText(ageGroups[ageCounter]);

		//shift dropdown arrow to the RIGHT instead of default LEFT position
		Display tempDisplay= getWindowManager().getDefaultDisplay();
		int width = tempDisplay.getWidth();
		ExpandList.setIndicatorBounds(width-50, width);

		// expand list setup code
		try{
			topLevelGroup = QuestionGroups();
			ExpAdapter = new ExpandListAdapter(SummaryPage.this, topLevelGroup);
			ExpandList.setAdapter(ExpAdapter);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

	// set the group and child of expandable list view 
	private ArrayList<ExpandListGroup> QuestionGroups(){
		ArrayList<ExpandListGroup> result = new ArrayList<ExpandListGroup>();

		ExpandListGroup no = new ExpandListGroup();
		no.setName("Not Yet");

		ExpandListGroup yes = new ExpandListGroup();
		yes.setName("Yes");

		ExpandListGroup maybe = new ExpandListGroup();
		maybe.setName("Not Sure");

		ExpandListGroup unanswered = new ExpandListGroup();
		unanswered.setName("Unanswered");

		ArrayList<ExpandListChild> no_items = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> yes_items = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> maybe_items = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> unanswered_items = new ArrayList<ExpandListChild>();

		SQLogic conn = new SQLogic(SummaryPage.this);

		try{
			conn.open();
			// grab questions and answers from database
			QAGroupings = conn.GetQuestionAnswerGroup(profile_number, currentmilestone);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			conn.close();
		}

		// set child groups and put a * in front of urgent questions
		for(int i = 0; i < QAGroupings.size(); i++){
			QuestionAnswerGroup current = QAGroupings.get(i);
			System.out.println(current.getQuestion() + "   " + current.getAnswer());

			if(current.getAnswer() == null){
				String temp = current.getQuestion();
				if(current.getUrgency() != 0)  // means its on the urgent list
					temp = "* " + temp;

				unanswered_items.add(new ExpandListChild(temp,null));
			}

			else if(current.getAnswer().equals(no_ans)){
				String temp = current.getQuestion();
				if(current.getUrgency() != 0)  // means its on the urgent list
					temp = "* " + temp;

				no_items.add(new ExpandListChild(temp,null));
			}

			else if(current.getAnswer().equals(yes_ans)){
				yes_items.add(new ExpandListChild(current.getQuestion(),null));
			}

			else if(current.getAnswer().equals(maybe_ans)){
				String temp = current.getQuestion();
				if(current.getUrgency() != 0)  // means its on the urgent list
					temp = "* " + temp;

				maybe_items.add(new ExpandListChild(current.getQuestion(),null));
			}

		}

		no.setItems(no_items);
		yes.setItems(yes_items);
		maybe.setItems(maybe_items);
		unanswered.setItems(unanswered_items);

		ExpandListGroup notes  = new ExpandListGroup();
		notes.setName("Notes");
		notes.setItems(getNoteChild());
		
		result.add(yes);
		result.add(no);
		result.add(maybe);
		result.add(unanswered);
		result.add(notes);

		return result;
	}


	// using this to retrieve note
	private ArrayList<ExpandListChild> getNoteChild(){
		SQLogic conn = new SQLogic(SummaryPage.this);
		JournalObject entry = null;

		try{
			conn.open();
			entry = conn.RetrieveJournalEntry(profile_number);
			conn.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			conn.close();
		}

		String result;
		if(entry.get(Integer.toString(currentmilestone)) == null)
			result = "";
		else
			result = entry.get(Integer.toString(currentmilestone)).Text;

		ExpandListChild temp = new ExpandListChild();
		temp.setName(result);


		ArrayList<ExpandListChild> n = new ArrayList<ExpandListChild>();
		n.add(temp);
		return n;
	}


	// returns index of wanted int
	private int IndexOf(int charac, int[] total){
		for(int i = 0; i < total.length; i++){
			if(total[i] == charac){
				return i;
			}
		}
		return -1;
	}

	// equivalent for string
	private int IndexOf(String charac, String[] total){
		for(int i = 0; i < total.length; i++){
			if(total[i].equals(charac)){
				return i;
			}
		}
		return -1;
	}

	// set the email layout, formats the milestones correctly
	private String  EmailGrid(){

		StringBuilder sb = new StringBuilder();

		SQLogic c = new SQLogic(SummaryPage.this);
		c.open();
		User curr = c.getUserData(profile_number);
		c.close();

		String age = ageGroups[ageCounter].replaceAll("years", "year").replaceAll("monthes", "month");
		sb.append("Here is a summary of " + curr.childname + "\'s "  + age + " Milestone Progress: <br><br>");


		String yesm = "<b> Milestone Questions Answered Yes to: </b>";
		sb.append(yesm);
		sb.append("<br><br>");
		for(int i = 0; i < topLevelGroup.get(0).getItems().size(); i++){
			String temp = topLevelGroup.get(0).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");

		}

		sb.append("<br><br>");
		sb.append("<b>Milestone Questions Answered No to:</b> <br><br>");
		for(int i = 0; i < topLevelGroup.get(1).getItems().size(); i++){
			String temp = topLevelGroup.get(1).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");
		}

		sb.append("<br><br>");
		sb.append("<b>Milestone Questions Answered Not Sure to:</b> <br><br>");
		for(int i = 0; i < topLevelGroup.get(2).getItems().size(); i++){
			String temp = topLevelGroup.get(2).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");
		}

		sb.append("<br><br>");
		sb.append("<b>Milestone Questions left Unanswered:</b> <br><br>");
		for(int i = 0; i < topLevelGroup.get(3).getItems().size(); i++){
			String temp = topLevelGroup.get(3).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");
		}
		sb.append("<br>");

		return sb.toString();
	}

}





